package com.maycari.captainbi.scheduled;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.maycari.captainbi.common.constant.CaptainBIConstant;
import com.maycari.captainbi.common.exception.BusinessException;
import com.maycari.captainbi.data.dto.Captain3Dto;
import com.maycari.captainbi.service.Captain3Service;
import com.maycari.captainbi.util.CaptainBIUtil;
import com.maycari.captainbi.util.MaycariRedis;
import com.maycari.tool.utils.DateUtil;
import com.maycari.tool.utils.ThreadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @Author: 王宏伟
 * @DateTime: 2021/4/1 11:36
 * @Description: 获取FBA销售报告列表
 */
@Component
public class Task3 implements ApplicationRunner {

    @Autowired
    private MaycariRedis maycariRedis;

    private static String start_time_str = "2021-03-01 00:00:00";

    private static String dataKey = "MAYCARI:DATAKEY3";

    private static String action = "http://cronapi.captainbi.com/index.php?m=cronapi&c=fba&a=getAmazonFbaInventoryRelList";

    @Autowired
    private Captain3Service captain3Service;

    //@Scheduled(cron = "0 0 1 * * ?")
    public void task() {
        System.out.println(1);

    }

    private void getData() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        int page = 1;
        int page_size = 100;

        Date start_time = maycariRedis.get(dataKey);
        if (start_time == null) {
            start_time = DateUtil.parse(start_time_str, DateUtil.PATTERN_DATETIME);
        }

        Date now = new Date();



        while (true) {
            JSONArray jsonArray = new JSONArray();
            //一天
            Date end_time = DateUtil.minusSeconds(DateUtil.plusDays(start_time, 1), 1);

            if (end_time.after(now)) {
                break;
            }
            while (true) {
                ThreadUtil.sleep(1000);
                TreeMap<String, String> params = new TreeMap<>();
                params.put("page", String.valueOf(page));
                params.put("page_size", String.valueOf(page_size));
                params.put("start_time", simpleDateFormat.format(start_time));
                params.put("end_time", simpleDateFormat.format(end_time));
                String result = CaptainBIUtil.sendRequest(CaptainBIConstant.CaptainBIUrl.url_3.value(), params);
                JSONObject jsonObject = JSON.parseObject(result, Feature.OrderedField);
                int code = jsonObject.getIntValue("code");
                if (code == 200) {
                    JSONArray data = jsonObject.getJSONArray("data");
                    if (data != null && data.size() > 0) {
                        if (data.size() >= 100) {
                            //可能还有数据  继续请求
                            jsonArray.addAll(data);
                            page++;
                        } else {
                            jsonArray.addAll(data);
                            break;
                        }
                    } else {
                        break;
                    }
                } else {
                    throw new BusinessException(String.format("task error :【%s】", jsonObject.getString("msg")));
                }
            }
            start_time = DateUtil.plusSeconds(end_time, 1);
            //captain3Service.insertBatch(coverData(jsonArray));
            maycariRedis.set(dataKey, start_time);
        }


    }

    private List<Captain3Dto> coverData(JSONArray jsonArray) {
        List<Captain3Dto> collect = jsonArray.stream().map(arr -> {
            JSONObject v = (JSONObject) arr;
            Captain3Dto dto = new Captain3Dto();
            dto.setId(v.getLong("id"));
            dto.setSiteId(v.getInteger("site_id"));
            dto.setInventoryId(v.getLong("inventory_id"));
            dto.setPInventoryId(v.getLong("p_inventory_id"));
            dto.setAmazonGoodsId(v.getLong("amazon_goods_id"));
            dto.setFnsku(v.getString("fnsku"));
            dto.setCreateTime(v.getInteger("create_time"));
            dto.setModifiedTime(v.getInteger("modified_time"));
            dto.setDaySale(v.getBigDecimal("day_sale"));
            dto.setDaySale1(v.getInteger("_1_day_sale"));
            dto.setDaySale3(v.getInteger("_3_day_sale"));
            dto.setDaySale7(v.getInteger("_7_day_sale"));
            dto.setDaySale14(v.getInteger("_14_day_sale"));
            dto.setDaySale30(v.getInteger("_30_day_sale"));
            dto.setDaySale60(v.getInteger("_60_day_sale"));
            dto.setDaySale90(v.getInteger("_90_day_sale"));
            dto.setAvgSale3(v.getBigDecimal("3_avg_sale"));
            dto.setAvgSale7(v.getBigDecimal("7_avg_sale"));
            dto.setAvgSale14(v.getBigDecimal("14_avg_sale"));
            dto.setAvgSale30(v.getBigDecimal("30_avg_sale"));
            dto.setAvgSale60(v.getBigDecimal("60_avg_sale"));
            dto.setAvgSale90(v.getBigDecimal("90_avg_sale"));
            dto.setDaySaleReturn1(v.getInteger("_1_day_sale_return"));
            dto.setDaySaleReturn3(v.getInteger("_3_day_sale_return"));
            dto.setDaySaleReturn7(v.getInteger("_7_day_sale_return"));
            dto.setDaySaleReturn14(v.getInteger("_14_day_sale_return"));
            dto.setDaySaleReturn30(v.getInteger("_30_day_sale_return"));
            dto.setDaySaleReturn60(v.getInteger("_60_day_sale_return"));
            dto.setDaySaleReturn90(v.getInteger("_90_day_sale_return"));
            dto.setAvgSaleReturn3(v.getBigDecimal("3_avg_sale_return"));
            dto.setAvgSaleReturn7(v.getBigDecimal("7_avg_sale_return"));
            dto.setAvgSaleReturn14(v.getBigDecimal("14_avg_sale_return"));
            dto.setAvgSaleReturn30(v.getBigDecimal("30_avg_sale_return"));
            dto.setAvgSaleReturn60(v.getBigDecimal("60_avg_sale_return"));
            dto.setAvgSaleReturn90(v.getBigDecimal("90_avg_sale_return"));
            dto.setDaySaleReturn(v.getBigDecimal("day_sale_return"));
            dto.setRavg3(v.getBigDecimal("ravg3"));
            dto.setRavg7(v.getBigDecimal("ravg7"));
            dto.setRavg14(v.getBigDecimal("ravg14"));
            dto.setRavg30(v.getBigDecimal("ravg30"));
            dto.setRavg60(v.getBigDecimal("ravg60"));
            dto.setRavg90(v.getBigDecimal("ravg90"));
            dto.setRavgDay(v.getBigDecimal("ravg_day"));
            dto.setOwnPrice(v.getBigDecimal("own_price"));
            dto.setOwnShipPrice(v.getBigDecimal("own_ship_price"));
            dto.setShipPrice(v.getBigDecimal("ship_price"));
            dto.setShipPriceTime(v.getInteger("ship_price_time"));
            dto.setStatus(v.getInteger("status"));
            dto.setQuantityForLocalFulfillment(v.getInteger("quantity_for_local_fulfillment"));
            dto.setReportModifiedTime(v.getInteger("report_modified_time"));
            return dto;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void run(ApplicationArguments args) {
        //getData();
    }
}

